package cn.xdf.Demo01;

import cn.xdf.dao.UserDao;
import cn.xdf.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath:spring.xml")
public class demo03_动态SQL {

    @Autowired
    private UserDao userDao;

    @Test
    public void test01(){
        //模拟前端传递的条件
        Map<String,Object> param=new HashMap<>();

//        param.put("username","明");
        param.put("sex","女");

        //做动态条件拼接
        Specification<User> spec = new Specification<User>() {

            /**
             *
             * @param root 根对象
             * @param criteriaQuery 离线对象
             * @param criteriaBuilder 条件构建对象
             * @return
             */
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {

                //存放所有的条件
                List<Predicate> predicateList=new ArrayList<>();

                //如果前端传了username，就对username模糊匹配
                if(param.get("username") !=null){
                    //获取path对象
                    Path<Object> username_path = root.get("username");

                    //获取表达式对象
                    Expression<String> username_exp = username_path.as(String.class);

                    //获取最终的条件对象
                    Predicate username_predicate = criteriaBuilder.like(username_exp, "%" + param.get("username").toString() + "%");

                    predicateList.add(username_predicate);
                }

                if(param.get("sex")!=null){
                    Path<Object> sex_path = root.get("sex");

                    //获取表达式对象
                    Expression<String> sex_exp = sex_path.as(String.class);

                    //获取最终的条件对象
                    Predicate sex_predicate = criteriaBuilder.equal(sex_exp,  param.get("sex").toString() );

                    predicateList.add(sex_predicate);
                }
                //获取path对象

                //where username like ? and sex =?
               Predicate[] predicates =new Predicate[predicateList.size()];
                //将集合中的每个元素都放到predicates数组,                 list转成数组toArray
                Predicate[] array = predicateList.toArray(predicates);

                Predicate and = criteriaBuilder.and(array);

                return and;
            }
        };

        List<User> userList = userDao.findAll(spec);
        for(User user:userList){
            System.out.println(user);
        }

    }




}
